/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/12/13
 */

import React from 'react';
import { Tree, Divider, List, Avatar, Input, Button } from 'antd';
import UserListPane from './UserListPane';
import styles from './Pane.less';
import PropTypes from 'prop-types';
import moment from 'moment';
import classNames from 'classnames';
import { arrayToTree } from 'utils';
import CreateForm from './CreateForm';
import UserSelectTransfer from './UserSelectTransfer';

const TreeNode = Tree.TreeNode;
const Search = Input.Search;

export default class DepartmentsPane extends React.Component {

  static propTypes = {
    organization: PropTypes.object.isRequired,
    organizationDepartment: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired,
  };

  constructor (props) {
    super(props);
    this.state = {
      selectedRows: [],
      unSelectedRows: [],

      createFormVisible: false,
    };
  }

  /**
   * 选择开发部门
   */
  _handleSelectDepartment = (value) => {
    // 设置当前开发部门

    const { dispatch, organizationDepartment: { departments } } = this.props;
    const currentDeptID = value[0];
    if (currentDeptID) {
      const dept = departments.find(_ => {
        return _.ID === currentDeptID;
      });
  
      // console.log('将要更改的部门', value);
      dispatch({
        type: 'organizationDepartment/changeCurrentDept',
        payload: {
          dept,
        },
      });
    }
  }

  /**
   * 将用户加入当前部门
   */
  _handleAddToDepartment = (users) => {
    const { dispatch } = this.props;
    if (!Array.isArray(users)) {
      users = Object.values(users);
    }
    // console.log(Array.isArray(Object.values(users)), 'isArray', Object.values(users));
    dispatch({
      type: 'organizationDepartment/addUserToDepartment',
      payload: {
        users, 
      },
    });
  }

  /**
   * 将用户从当前部门移除
   */
  _handleRemoveFromDepartment = (users) => {
    const { dispatch } = this.props;
    if (!Array.isArray(users)) {
      users = Object.values(users);
    }
    dispatch({
      type: 'organizationDepartment/removeUserFromDepartment',
      payload: {
        users,
      },
    });
    console.log(users, '---- remove ----');
  }

  _toggleCreateFormModal = () => {
    this.setState({
      createFormVisible: !this.state.createFormVisible,
    });
  }

  _handleCreateFormCancel = () => {
    this._toggleCreateFormModal();
  }

  _handleCreateFormSubmit = (values) => {
    // console.log(values);
    const parent = values.parentID.length > 0 ? values.parentID[values.parentID.length - 1] : "";
    const postData = {
      name: values.name,
      parent,
      description: values.description,
    };

    const { dispatch } = this.props;
    dispatch({
      type: 'organizationDepartment/createDepartment',
      payload: {
        postData, 
      },
    });
  }

  _generateDeptsTree = () => {
    const { departments } = this.props.organizationDepartment;
    const deptTree = arrayToTree(departments, 'ID', 'ParentID', 'children');
    // let firstDept = null;
    const toTreesComponent = (depts) => {
      return depts.map(dept => {
        if (dept.children && Array.isArray(dept.children)) {
          return (
            <TreeNode title={dept.Name} key={dept.ID} >
              {toTreesComponent(dept.children)}
            </TreeNode>
          );
        }
        return <TreeNode title={dept.Name} key={dept.ID} />
      });
    };

    return (
      <Tree
        showLine
        onSelect={this._handleSelectDepartment}
        defaultExpandedKeys={['0-0-0']}
      >
        {toTreesComponent(deptTree)}
      </Tree>
    );
  }

  __loadAllUsers = (page) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'organizationDepartment/loadAllUsers',
      payload: {
        isLoad: true,
        page,
        limit: 10,
      },
    });
  };

  __loadUserFromDept = (page) => {
    
  }

  __selectNotInUser = (userID) => {
    const { willAddUsers } = this.state;
    willAddUsers.push(userID);
    this.setState({
      willLeaveUsers: [],
      willAddUsers,
    });
  };

  __selectHasInUser = (userID) => {
    const { willLeaveUsers } = this.state;
    willLeaveUsers.push(userID);
    this.setState({
      willLeaveUsers,
      willAddUsers: [],
    });
  };

  render () {
    const { organization, organizationDepartment } = this.props;

    return (
      <div className={styles.paneContainer} >
        <CreateForm 
          visible={this.state.createFormVisible}
          depts={this.props.organizationDepartment.departments}
          handleCancel={this._handleCreateFormCancel}
          handleSubmit={this._handleCreateFormSubmit}
        />
        <div className={styles.card} >
          <div className={styles.header}>
            <div className={styles.title}>
              <h3>{organization ? organization.Name : '-'}</h3>
            </div>
            <div className={styles.btn}>
              <a onClick={this._toggleCreateFormModal}>新增部门</a>
            </div>
          </div>
          <div className={styles.content} >
            <div className={styles.search}>
              <Search
                placeholder="搜索"
                onSearch={value => console.log(value)}
              />
            </div>
            {this._generateDeptsTree()}
          </div>
        </div>
        <Divider type="vertical" dashed={false} className={styles.divider} />
        <UserSelectTransfer
          title={organizationDepartment.currentDept && organizationDepartment.currentDept.Name}
          folderLength={(organizationDepartment.departments || []).length}
          selectedRows={organizationDepartment.selectedUsers}
          allRows={organizationDepartment.allUsers}
          hasMore={false}
          onLoadRightList={this.__loadAllUsers}
          onAdd={users => this._handleAddToDepartment(users)}
          onRemove={users => this._handleRemoveFromDepartment(users)}
        />
      </div>
    );
  }
}
